/**
  * 封装了nodejs 的mysql工具包，并加入了promise用于事务处理
  * @module 数据库连接
 * @author 徐灿
 * @date 2018-7-26
  */

'use strict';

const mysql = require('mysql');
const {MySQL} = require('../../Config').dev;

function getConnection() {
    let conn = mysql.createConnection({
        host: MySQL.host,
        port: MySQL.port,
        user: MySQL.userName,
        password: MySQL.password,
        database: MySQL.database,
        connectionLimit: MySQL.connectionLimit,
        debug: MySQL.debugOptions,
        multipleStatements: MySQL.multipleStatements,
    });
    return new Promise(function (resolve, reject) {
        conn.connect(function (err) {
            if (err) {
                reject(err);
            } else {
                resolve(conn);
            }
        });
    });
}

function query(conn, sql, params) {
    let p = [];
    if (params) p = p.concat(params);
    return new Promise(function (resolve, reject) {
        conn.query(sql, p, function (err, rows) {
            if (err) {
                reject(err);
            } else {
                resolve(rows);
            }
        });
    })
}

function end(conn) {
    return new Promise(function (resolve, reject) {
        conn.end(function (err) {
            if (err) {
                reject(err);
            } else {
                resolve({success: true});
                // return true;
            }
        });
    });
}


exports.query = query;
exports.end = end;
exports.connect = getConnection;
